import React, { useState, useMemo, useCallback, useEffect } from 'react';
import Loading from "@/component/layout/loading/loading";

import { ListView, Toast } from 'antd-mobile';

let viewMap = new Map();

const CommonList = (props) => {
  const { viewCmp: ViewCmp, param, method, mapkey = 'id', update } = props;
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(false);

  const blob = useMemo(() => {
    let obj = {};
    list.map(item => obj[item[mapkey]] = item)
    return obj
  }, [list, mapkey])

  const footer = useMemo(() => {
    if (loading) return <Loading/>
    if (loaded && list.length === 0) return <div className="nodata">
      <img src={require('../../../assests/img/nodata.png')} alt=""/>
      <p>暂无数据</p>
    </div>
    if (loaded) return '已经到底啦~'

  }, [loading, loaded, list.length])

  const getData = useCallback(async () => {
    if (param.pageIndex === 1) {
      setList([])
      setLoaded(false)
      viewMap.clear();
    }
    setLoading(true)
    try {
      let res = await method({ ...param });
      setLoading(false)
      if (res.errorCode === 0) {
        if (res.source && res.source.items) {
          let data = res.source.items;
          data.map(item => viewMap.set(item[mapkey], item))
          setList(pre => {
            if (param.pageIndex === 1) {
              return [...data]
            } else {
              return [...pre, ...data]
            }
          })
          if (viewMap.size === res.source.total) {
            setLoaded(true)
          }
        }
      } else {
        Toast.fail('服务器发生错误')
        setLoaded(true)
      }

    } catch (error) {
      setLoading(false)
    }
  }, [mapkey, method, param])

  const getRowData = useCallback((dataBlob, sectionID, rowID) => {
    return dataBlob[rowID]
  }, [])

  // const getSectionData = useCallback((dataBlob, sectionID) => {
  //   return headerData[sectionID]
  // }, [])

  const getDataSource = useMemo(() => {
    return new ListView.DataSource({
      getRowData,
      rowHasChanged: (row1, row2) => row1 !== row2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
      // getSectionHeaderData: getSectionData,
      // dataBlob:data1, // 数据存储
      // sectionID:data1, // section数组
      // rowID:data1 // 一个section里面的数据
    }).cloneWithRowsAndSections(blob, [1], [list.map(item => item[mapkey])])
  }, [blob, getRowData, list, mapkey])

  const row = useCallback((rowData, sectionID, rowID) => {
    if (ViewCmp) return <ViewCmp data={rowData} key={rowID} />
  }, [ViewCmp])

  const onEndReached = useCallback(() => {
    if (loaded) return
    if (update) update();
  }, [loaded, update])

  useEffect(() => {
    getData();
  }, [getData])

  return <ListView
    dataSource={getDataSource}
    key={'id'}
    renderFooter={() => (<div style={{ textAlign: 'center' }}>
      {footer}
    </div>)}
    // ref={el => lv = el}
    // renderHeader={() => <span>header</span>}
    // renderSectionHeader={sectionData => (
    //   <div>{`Task SectionHeader`}</div>
    // )}
    // renderBodyComponent={() => <div>123</div>}
    // renderSeparator={separator}
    initialListSize={20}
    renderRow={row}
    style={{
      height: '100%',
      overflow: 'auto',
    }}
    // onScroll={() => { console.log('scroll'); }}
    scrollRenderAheadDistance={500}
    onEndReached={onEndReached}
    onEndReachedThreshold={20}
  />

}


export default React.memo(CommonList)